package com.zhouk.ams.wx;

import com.zhouk.ams.wx.utils.WxUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信GET 校验
 * 微信POST 发送消息
 * Create By Zhouke on 2017/09/21
 */
@WebServlet(name = "WxServlet", urlPatterns = "/wx")
public class WxServlet extends HttpServlet {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private static final String TOKEN = "yonyou_zhouke";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        logger.info("开始校验签名");
        /**
         * 接收微信服务器发送请求时传递过来的4个参数
         */
        //微信加密签名signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");
        //排序
        String sortString = WxUtils.sort(TOKEN, timestamp, nonce);
        //加密
        String mySignature = WxUtils.sha1(sortString);
        //校验签名
        if (mySignature != null && mySignature != "" && mySignature.equals(signature)) {
            logger.info("签名校验通过。");
            //如果检验成功输出echostr，微信服务器接收到此输出，才会确认检验完成。
            resp.getWriter().write(echostr);
        } else {
            logger.info("签名校验失败.");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        WxMsg wxMsg = WxUtils.createWxMsg(req);
        // 构造返回消息，XML格式
        String respMsg = WxUtils.createWxRespMsg(wxMsg);

        // 回复消息
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().print(respMsg);

    }




}
